// stores/websocket.js
import { defineStore } from 'pinia'
import { Client } from '@stomp/stompjs'

export const useWebSocketStore = defineStore('websocket', {
  state: () => ({
    stompClient: null,
    connected: false,
    messages: [],
    subscriptions: new Map(),
    currentChannel: JSON.parse(localStorage.getItem('user') || '{}')?.id || ""
  }),

  actions: {
    // 初始化 WebSocket 连接（添加连接状态日志）
    initConnection() {
      console.log('[WebSocket] 开始初始化连接...')
      this.stompClient = new Client({
        // brokerURL: `http://${localStorage.getItem('localIP')}:6001/ws`,
        brokerURL: `ws://${localStorage.getItem('localIP')}:6001/ws`,

        reconnectDelay: 5000,
        onConnect: () => {
          console.log('[WebSocket] 连接成功 ✅')
          this.connected = true
          this.subscribe(JSON.parse(localStorage.getItem('user')).id)
        },
        onDisconnect: () => {
          console.warn('[WebSocket] 连接断开 ❌')
          this.connected = false
        },
        onStompError: (error) => {
          console.error('[WebSocket] STOMP协议错误:', error)
        }
      })
      this.stompClient.activate()
    },

    // 订阅频道（添加订阅日志）
    subscribe(channel) {
      if (!this.stompClient || !this.connected) {
        console.warn(`[WebSocket] 无法订阅 ${channel}（连接未就绪）`)
        return
      }

      const topic = `/topic/${channel}`
      console.log(`[WebSocket] 订阅频道: ${topic} ...`)

      const subscription = this.stompClient.subscribe(topic, (message) => {
        const logMsg = `[${channel}] ${message.body}`
        console.log('[WebSocket] 收到消息:', logMsg)
        this.messages.push(logMsg)
      })
      
      this.subscriptions.set(channel, {
        id: subscription.id,
        unsubscribe: subscription.unsubscribe
      })
      this.currentChannel = channel
      console.log(`[WebSocket] 订阅成功，当前频道数: ${this.subscriptions.size}`)
    },

    // 发送消息（添加消息发送日志）
    sendMessage(message) {
      if (this.stompClient?.connected) {
        const destination = `/app/channel/${this.currentChannel}`
        console.log('[WebSocket] 发送消息:', { destination, message })
        this.stompClient.publish({
          destination,
          body: message
        })
      } else {
        console.error('[WebSocket] 发送失败：连接未建立')
      }
    },

    // 清理订阅（添加清理日志）
    cleanup() {
      console.log('[WebSocket] 开始清理订阅...')
      this.subscriptions.forEach(sub => {
        console.log('[WebSocket] 取消订阅 ID:', sub.id)
        sub.unsubscribe()
      })
      this.subscriptions.clear()
      this.messages = []
      console.log('[WebSocket] 清理完成')
    },

    // 重新订阅（添加重订阅日志）
    resubscribeAll() {
      console.log('[WebSocket] 开始重新订阅...')
      const channels = Array.from(this.subscriptions.keys())
      channels.forEach(ch => {
        console.log('[WebSocket] 重新订阅:', ch)
        this.subscribe(ch)
      })
    }
  }
})